import { login } from "@/apis/user";
import {
  setToken,
  setUser,
  getUser,
  removeUser,
  removeToken
} from "@/utils/app";
import { getAccBasic } from "@/apis/account";

const state = {
  isCollapse: JSON.parse(sessionStorage.getItem("isCollapse")) || false, // 控制菜单是否折叠
  token: "",
  user: getUser() || "",
  acc_ids: []
};

const getters = {
  isCollapse: state => !state.isCollapse
};

const mutations = {
  setCollapse(state) {
    state.isCollapse = !state.isCollapse;
    // html5本地存储 只能存字符串
    sessionStorage.setItem("isCollapse", JSON.stringify(state.isCollapse));
  },
  SET_TOKEN(state, value) {
    state.token = value;
  },
  SET_USER(state, value) {
    state.user = value;
  },
  SET_ACC_IDS(state, value) {
    state.acc_ids = value;
  }
};

const actions = {
  // 可以处理回调
  login({ commit }, requestData) {
    // content： 上下文
    // requestData distpatch传过来的参数
    return new Promise((resolve, reject) => {
      // 接口
      login(requestData)
        .then(response => {
          let data = response.data.data;
          commit("SET_TOKEN", data.token);
          commit("SET_USER", data.user);
          setToken(data.token);
          setUser(data.user);
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  logout({ commit }) {
    return new Promise(resolve => {
      removeUser();
      removeToken();
      commit("SET_TOKEN", "");
      commit("SET_USER", "");
      resolve();
    });
  },
  // 获取基金账户列表
  getAccIds({ commit }) {
    return new Promise((resolve, reject) => {
      getAccBasic()
        .then(response => {
          let data = response.data;
          commit("SET_ACC_IDS", data);
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
